package com.kexio.email.builder;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.kexio.email.entity.EmailAttachment;
import com.kexio.email.entity.EmailRecord;
import com.kexio.email.enums.EmailType;

import cn.hutool.core.util.IdUtil;

/**
 * 邮件构建器
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
public class EmailBuilder {
    
    private EmailRecord emailRecord;
    private List<EmailAttachment> attachments;
    
    private EmailBuilder() {
        this.emailRecord = new EmailRecord();
        this.attachments = new ArrayList<>();
        this.emailRecord.setId(IdUtil.fastSimpleUUID());
    }
    
    /**
     * 创建邮件构建器
     */
    public static EmailBuilder create() {
        return new EmailBuilder();
    }
    
    /**
     * 设置发件人
     */
    public EmailBuilder from(String email, String name) {
        emailRecord.setFromEmail(email);
        emailRecord.setFromName(name);
        return this;
    }
    
    /**
     * 设置发件人 (仅邮箱)
     */
    public EmailBuilder from(String email) {
        emailRecord.setFromEmail(email);
        return this;
    }
    
    /**
     * 设置收件人
     */
    public EmailBuilder to(String... emails) {
        emailRecord.setToEmails(String.join(";", emails));
        return this;
    }
    
    /**
     * 设置抄送
     */
    public EmailBuilder cc(String... emails) {
        emailRecord.setCcEmails(String.join(";", emails));
        return this;
    }
    
    /**
     * 设置密送
     */
    public EmailBuilder bcc(String... emails) {
        emailRecord.setBccEmails(String.join(";", emails));
        return this;
    }
    
    /**
     * 设置邮件主题
     */
    public EmailBuilder subject(String subject) {
        emailRecord.setSubject(subject);
        return this;
    }
    
    /**
     * 设置文本内容
     */
    public EmailBuilder textContent(String content) {
        emailRecord.setContent(content);
        emailRecord.setEmailType(EmailType.TEXT.getCode());
        return this;
    }
    
    /**
     * 设置HTML内容
     */
    public EmailBuilder htmlContent(String htmlContent) {
        emailRecord.setContent(htmlContent);
        emailRecord.setEmailType(EmailType.HTML.getCode());
        return this;
    }
    
    /**
     * 设置模板
     */
    public EmailBuilder template(String templateCode, Map<String, Object> params) {
        emailRecord.setTemplateId(templateCode);
        emailRecord.setTemplateParams(params != null ? params.toString() : null);
        emailRecord.setEmailType(EmailType.TEMPLATE.getCode());
        return this;
    }
    
    /**
     * 添加附件
     */
    public EmailBuilder attach(EmailAttachment attachment) {
        if (attachment != null && attachment.isValid()) {
            attachments.add(attachment);
        }
        return this;
    }
    
    /**
     * 添加附件 (字节数组)
     */
    public EmailBuilder attach(String name, String contentType, byte[] content) {
        return attach(new EmailAttachment(name, contentType, content));
    }
    
    /**
     * 添加附件 (文件路径)
     */
    public EmailBuilder attach(String name, String filePath) {
        return attach(new EmailAttachment(name, filePath));
    }
    
    /**
     * 设置优先级 (1-5, 1最高)
     */
    public EmailBuilder priority(int priority) {
        emailRecord.setPriority(priority);
        return this;
    }
    
    /**
     * 设置业务类型
     */
    public EmailBuilder businessType(String businessType) {
        emailRecord.setBusinessType(businessType);
        return this;
    }
    
    /**
     * 设置业务关键字
     */
    public EmailBuilder businessKey(String businessKey) {
        emailRecord.setBusinessKey(businessKey);
        return this;
    }
    
    /**
     * 设置是否异步发送
     */
    public EmailBuilder async(boolean isAsync) {
        emailRecord.setIsAsync(isAsync);
        return this;
    }
    
    /**
     * 设置最大重试次数
     */
    public EmailBuilder maxRetry(int maxRetry) {
        emailRecord.setMaxRetryCount(maxRetry);
        return this;
    }
    
    /**
     * 构建邮件记录
     */
    public EmailRecord build() {
        // 基本验证
        if (emailRecord.getToEmails() == null || emailRecord.getToEmails().trim().isEmpty()) {
            throw new IllegalArgumentException("收件人不能为空");
        }
        
        if (emailRecord.getSubject() == null || emailRecord.getSubject().trim().isEmpty()) {
            throw new IllegalArgumentException("邮件主题不能为空");
        }
        
        // 设置附件信息
        if (!attachments.isEmpty()) {
            // 这里可以将附件信息序列化为JSON存储
            emailRecord.setAttachments("attachments:" + attachments.size());
            if (emailRecord.getEmailType().equals(EmailType.TEXT.getCode()) || 
                emailRecord.getEmailType().equals(EmailType.HTML.getCode())) {
                emailRecord.setEmailType(EmailType.RICH.getCode());
            }
        }
        
        return emailRecord;
    }
    
    /**
     * 获取附件列表
     */
    public List<EmailAttachment> getAttachments() {
        return new ArrayList<>(attachments);
    }
    
    /**
     * 验证邮件地址格式
     */
    public static boolean isValidEmail(String email) {
        if (email == null || email.trim().isEmpty()) {
            return false;
        }
        return email.matches("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$");
    }
    
    /**
     * 快速创建文本邮件
     */
    public static EmailBuilder textEmail(String to, String subject, String content) {
        return create().to(to).subject(subject).textContent(content);
    }
    
    /**
     * 快速创建HTML邮件
     */
    public static EmailBuilder htmlEmail(String to, String subject, String htmlContent) {
        return create().to(to).subject(subject).htmlContent(htmlContent);
    }
    
    /**
     * 快速创建模板邮件
     */
    public static EmailBuilder templateEmail(String to, String templateCode, Map<String, Object> params) {
        return create().to(to).template(templateCode, params);
    }
}
